package com.compty.core.framework.plugin.payment.tenpay;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.compty.core.framework.context.webcontext.ThreadContextHolder;
import com.compty.core.framework.plugin.AbstractPaymentPlugin;
import com.compty.core.framework.plugin.payment.IPaymentEvent;
import com.compty.core.framework.util.HttpUtil;
import com.compty.paint.domain.Order;
import com.tenpay.RequestHandler;
import com.tenpay.util.TenpayUtil;

/**
 * 财付通(即时到账)支付插件
 * @author 朱庆辉
 *
 */
public class TenpayPlugin  extends AbstractPaymentPlugin implements IPaymentEvent{
	
	private final String  key = "yq36050219761201rx43042619790811";////平台商密钥
	private final String  chnid = "1213029301";//平台商帐号
	
	public String onCallBack() {
		
		//---------------------------------------------------------
		//财付通支付应答（处理回调）示例，商户按照此文档进行开发即可
		//---------------------------------------------------------
		
		HttpServletRequest request  =  ThreadContextHolder.getHttpRequest();
		
		//------------------------------
		String order_no = request.getParameter("out_trade_no");	        //获取订单号
		
		this.paySuccess( order_no );
		
		return "success";	//请不要修改或删除	
	}
	
	public String onPay(Order order) {
		
		HttpServletRequest request  =  ThreadContextHolder.getHttpRequest();
		HttpServletResponse response  = ThreadContextHolder.getHttpResponse();

		//回调通知URL
		String notify_url = HttpUtil.getFullContext(request)+"/user/tenpay/notify_url.jsp";

		//支付显示URL
		String return_url = HttpUtil.getFullContext(request)+"/user/tenpay/return_url.jsp";

		//创建支付请求对象
		RequestHandler reqHandler = new RequestHandler(request, response);
		reqHandler.init();
		//设置密钥
		reqHandler.setKey(key);
		//设置支付网关
		reqHandler.setGateUrl("https://gw.tenpay.com/gateway/pay.htm");
		
		//-----------------------------
		//设置支付参数
		//-----------------------------
		reqHandler.setParameter("partner", chnid);		        //商户号
		reqHandler.setParameter("out_trade_no", order.getSequenceNo());		//商家订单号
		reqHandler.setParameter("total_fee", formatPrice( order.getOrder_amount()*100 ));			        //商品金额,以分为单位
		reqHandler.setParameter("return_url", return_url);		    //交易完成后跳转的URL
		reqHandler.setParameter("notify_url", notify_url);		    //接收财付通通知的URL
		reqHandler.setParameter("body",  "支付订单"+order.getSequenceNo());	//商品描述
		reqHandler.setParameter("bank_type", "DEFAULT");		    //银行类型(中介担保时此参数无效)
		reqHandler.setParameter("spbill_create_ip",request.getRemoteAddr());   //用户的公网ip，不是商户服务器IP
		reqHandler.setParameter("fee_type", "1");                    //币种，1人民币
		reqHandler.setParameter("subject", "订单ID：["+order.getId()+"],"+order.getGoods());              //商品名称(中介交易时必填)

		//系统可选参数
		reqHandler.setParameter("sign_type", "MD5");                //签名类型,默认：MD5
		reqHandler.setParameter("service_version", "1.0");			//版本号，默认为1.0
		reqHandler.setParameter("input_charset", "utf-8");            //字符编码
		reqHandler.setParameter("sign_key_index", "1");             //密钥序号


		//业务可选参数
		reqHandler.setParameter("attach", "");                      //附加数据，原样返回
		reqHandler.setParameter("product_fee", "");                 //商品费用，必须保证transport_fee + product_fee=total_fee
		reqHandler.setParameter("transport_fee", "0");               //物流费用，必须保证transport_fee + product_fee=total_fee
		reqHandler.setParameter("time_start", TenpayUtil.getCurrTime());            //订单生成时间，格式为yyyymmddhhmmss
		reqHandler.setParameter("time_expire", "");                 //订单失效时间，格式为yyyymmddhhmmss
		reqHandler.setParameter("buyer_id", "");                    //买方财付通账号
		reqHandler.setParameter("goods_tag", "");                   //商品标记
		reqHandler.setParameter("trade_mode", "1");                 //交易模式，1即时到账(默认)，2中介担保，3后台选择（买家进支付中心列表选择）
		reqHandler.setParameter("transport_desc", "");              //物流说明
		reqHandler.setParameter("trans_type", "1");                  //交易类型，1实物交易，2虚拟交易
		reqHandler.setParameter("agentid", "");                     //平台ID
		reqHandler.setParameter("agent_type", "");                  //代理模式，0无代理(默认)，1表示卡易售模式，2表示网店模式
		reqHandler.setParameter("seller_id", "");                   //卖家商户号，为空则等同于partner

		//请求的url
		try {
			String requestUrl = reqHandler.getRequestURL();
			return "<script>location.href=\""+requestUrl+"\"</script>";
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "财付通支付错误!";
		}
	}
	

	public String onPreStore(Double order_amount) {
		// TODO Auto-generated method stub
		//---------------生成订单号 开始------------------------
		//当前时间 yyyyMMddHHmmss
		String currTime = TenpayUtil.getCurrTime();
		//8位日期
		String strTime = currTime.substring(8, currTime.length());
		//四位随机数
		String strRandom = TenpayUtil.buildRandom(4) + "";
		//10位序列号,可以自行调整。
		String strReq = strTime + strRandom;
		//订单号，此处用时间加随机数生成，商户根据自己情况调整，只要保持全局唯一就行
		String out_trade_no = strReq;
		//---------------生成订单号 结束------------------------
		
		HttpServletRequest request  =  ThreadContextHolder.getHttpRequest();
		HttpServletResponse response  = ThreadContextHolder.getHttpResponse();
		
		String amount_money = request.getParameter("amount_money");
		Double modify_advance = Double.valueOf(amount_money);//充值金额

		//回调通知URL
		String mch_returl = this.getPreStoreCallBackUrl();

		//支付显示URL
		String show_url = this.getPreStoreCallBackUrl();

		//创建支付请求对象
		RequestHandler reqHandler = new RequestHandler(request, response);
		reqHandler.init();
		//设置密钥
		reqHandler.setKey(key);
		//设置支付网关
		reqHandler.setGateUrl("https://gw.tenpay.com/gateway/pay.htm");
		
		//-----------------------------
		//设置支付参数
		//-----------------------------
		reqHandler.setParameter("partner", chnid);		        //商户号
		reqHandler.setParameter("out_trade_no", out_trade_no);		//商家订单号
		reqHandler.setParameter("total_fee",formatPrice( modify_advance*100 ));	 //商品金额,以分为单位
		reqHandler.setParameter("return_url", show_url);		    //交易完成后跳转的URL
		reqHandler.setParameter("notify_url", mch_returl);		    //接收财付通通知的URL
		reqHandler.setParameter("body", "充值");	                    //商品描述
		reqHandler.setParameter("bank_type", "DEFAULT");		    //银行类型(中介担保时此参数无效)
		reqHandler.setParameter("spbill_create_ip",request.getRemoteAddr());   //用户的公网ip，不是商户服务器IP
		reqHandler.setParameter("fee_type", "1");                    //币种，1人民币
		reqHandler.setParameter("subject", "充值");              //商品名称(中介交易时必填)

		//系统可选参数
		reqHandler.setParameter("sign_type", "MD5");                //签名类型,默认：MD5
		reqHandler.setParameter("service_version", "1.0");			//版本号，默认为1.0
		reqHandler.setParameter("input_charset", "utf-8");            //字符编码
		reqHandler.setParameter("sign_key_index", "1");             //密钥序号


		//业务可选参数
		reqHandler.setParameter("attach", "");                      //附加数据，原样返回
		reqHandler.setParameter("product_fee", "");                 //商品费用，必须保证transport_fee + product_fee=total_fee
		reqHandler.setParameter("transport_fee", "0");               //物流费用，必须保证transport_fee + product_fee=total_fee
		reqHandler.setParameter("time_start", currTime);            //订单生成时间，格式为yyyymmddhhmmss
		reqHandler.setParameter("time_expire", "");                 //订单失效时间，格式为yyyymmddhhmmss
		reqHandler.setParameter("buyer_id", "");                    //买方财付通账号
		reqHandler.setParameter("goods_tag", "");                   //商品标记
		reqHandler.setParameter("trade_mode", "1");                 //交易模式，1即时到账(默认)，2中介担保，3后台选择（买家进支付中心列表选择）
		reqHandler.setParameter("transport_desc", "");              //物流说明
		reqHandler.setParameter("trans_type", "1");                  //交易类型，1实物交易，2虚拟交易
		reqHandler.setParameter("agentid", "");                     //平台ID
		reqHandler.setParameter("agent_type", "");                  //代理模式，0无代理(默认)，1表示卡易售模式，2表示网店模式
		reqHandler.setParameter("seller_id", "");                   //卖家商户号，为空则等同于partner

		//请求的url
		try {
			String requestUrl = reqHandler.getRequestURL();
			return "<script>location.href=\""+requestUrl+"\"</script>";
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "财付通支付错误!";
		}
		
	}
	
	protected String getPreStoreCallBackUrl(){
		HttpServletRequest request  =  ThreadContextHolder.getHttpRequest();
		String serverName =request.getServerName();
		String paymentId = request.getParameter("paymentid");
		String amount_money = request.getParameter("amount_money");
		int port  = request.getLocalPort();
		String contextPath = request.getContextPath();
		return "http://"+serverName+":"+port+contextPath+"/customer/paywidget.do?action=prestore_success&paymentid="+paymentId+"&amount_money="+amount_money;
	}

	
	private String formatPrice(Double price ){
       java.text.DecimalFormat   myformat=new   java.text.DecimalFormat("#");   
       return  myformat.format(price); 
	}

	
	public void register() {
		
	}

	
	public String getAuthor() {
		
		return "kingapex";
	}

	
	public String getId() {
		return "tenpay_med";
	}

	
	public String getName() {
		return "财付通（即时到账）";
	}

	
	public String getType() {
		return "payment";
	}

	
	public String getVersion() {
		return "1.0";
	}

	
	public void perform(Object... params) {
		
	}
	
}
